	<template>
	<div class="house-container">
		<!-- 搜索框 -->
		<div class="search-bar">
			<div class="search-input-container">
				<a-input v-model:value="searchQuery" placeholder="请输入区域、地点或公寓名称" class="search-input" />
				<a-button @click="search" class="search-button">搜索</a-button>
			</div>
		</div>

		<!-- 筛选条件 -->
		<div class="filter-container">
			<!-- 户型筛选 -->
			<div class="filter-group">
				<span class="filter-title">户型：</span>
				<div class="filter-options">
					<span
						v-for="type in houseTypes"
						:key="type"
						:class="['filter-option', { active: selectedHouseType === type }]"
						@click="
							this.selectedHouseType = type;
							filterHouses();
						"
					>
						{{ type }}
					</span>
				</div>
			</div>

			<!-- 租金筛选 -->
			<div class="filter-group">
				<span class="filter-title">租金：</span>
				<div class="filter-options">
					<span
						v-for="(price, index) in priceRanges"
						:key="price"
						:class="['filter-option', { active: selectedPriceRange === price && !customPriceMin && !customPriceMax }]"
						@click="
							selectedPriceRange = price;
							customPriceMin = null;
							customPriceMax = null;
							filterHouses();
						"
					>
						{{ price }}
					</span>
					<div class="custom-range">
						<a-input-number v-model:value="customPriceMin" placeholder="最小值" :style="{ width: '80px' }" />
						<span class="range-divider"> - </span>
						<a-input-number v-model:value="customPriceMax" placeholder="最大值" :style="{ width: '80px' }" />
						<a-button type="primary" size="small" @click="filterHouses" class="custom-range-button"> 确定 </a-button>
					</div>
				</div>
			</div>

			<!-- 面积筛选 -->
			<div class="filter-group">
				<span class="filter-title">面积：</span>
				<div class="filter-options">
					<span
						v-for="area in areaRanges"
						:key="area"
						:class="['filter-option', { active: selectedAreaRange === area && !customAreaMin && !customAreaMax }]"
						@click="
							selectedAreaRange = area;
							customAreaMin = null;
							customAreaMax = null;
							filterHouses();
						"
					>
						{{ area }}
					</span>
					<div class="custom-range">
						<a-input-number v-model:value="customAreaMin" placeholder="最小值" :style="{ width: '80px' }" />
						<span class="range-divider"> - </span>
						<a-input-number v-model:value="customAreaMax" placeholder="最大值" :style="{ width: '80px' }" />
						<a-button type="primary" size="small" @click="filterHouses" class="custom-range-button"> 确定 </a-button>
					</div>
				</div>
			</div>

			<!-- 楼层筛选 -->
			<div class="filter-group">
				<span class="filter-title">楼层：</span>
				<div class="filter-options">
					<span
						v-for="floor in floors"
						:key="floor"
						:class="['filter-option', { active: selectedFloor === floor && !customFloorMin && !customFloorMax }]"
						@click="
							selectedFloor = floor;
							customFloorMin = null;
							customFloorMax = null;
							filterHouses();
						"
					>
						{{ floor }}
					</span>
					<div class="custom-range">
						<a-input-number v-model:value="customFloorMin" placeholder="最小楼层" :style="{ width: '80px' }" />
						<span class="range-divider"> - </span>
						<a-input-number v-model:value="customFloorMax" placeholder="最大楼层" :style="{ width: '80px' }" />
						<a-button size="small" @click="filterHouses" class="custom-range-button"> 确定</a-button>
					</div>
				</div>
			</div>

			<!-- 商圈筛选 -->
			<div class="filter-group">
				<span class="filter-title">商圈：</span>
				<div class="filter-options">
					<span
						v-for="district in businessArea"
						:key="district"
						:class="['filter-option', { active: selectedDistrict === district }]"
						@click="
							selectedDistrict = district;
							filterHouses();
						"
					>
						{{ district }}
					</span>
				</div>
			</div>

			<!-- 地铁站筛选 -->
			<div class="filter-group">
				<span class="filter-title">地铁站：</span>
				<div class="filter-options">
					<span
						v-for="station in subwayStations"
						:key="station"
						:class="['filter-option', { active: selectedStation === station }]"
						@click="
							selectedStation = station;
							filterHouses();
						"
					>
						{{ station }}
					</span>
				</div>
			</div>
		</div>

		<!-- 排序和总条数 -->
		<div class="sort-container">
			<div class="sort-options">
				<span
					v-for="option in sortOptions"
					:key="option.label"
					:class="['sort-option', { active: selectedSort === option.value }]"
					@click="setSort(option.value)"
				>
					{{ option.label }}
					<!-- 判断是否显示箭头 -->
					<span v-if="selectedSort === option.value && selectedSort !== null">
						{{ sortOrder === 'asc' ? '↑' : '↓' }}
					</span>
				</span>
			</div>
			<div class="total-count">共找到 {{ totalCount }} 套房源</div>
		</div>

		<!-- 房源列表页 -->
		<a-spin :spinning="loading">
			<div v-if="houses.length > 0" class="house-list">
				<div class="house-item" v-for="(house, index) in houses" :key="index" @click="goToDetails(house.id)">
					<div class="house-image">
						<img :src="house.imageUrls[0]" alt="房源图片" />
					</div>
					<div class="house-details">
						<text class="house-title">{{ house.title }}</text>
						<div class="house-info">
							<div class="field-row">
								<span class="field">{{ house.houseType }}</span>
								<span class="field">{{ house.area }}㎡</span>
								<span class="field">{{ house.businessArea }}</span>
							</div>
							<div class="field-row">
								<span class="field">近{{ house.subwayStation }}地铁站</span>
								<span class="field" v-if="house.community">{{ house.community }}</span>
							</div>
						</div>
						<div class="house-price">
							<span class="price">￥{{ house.price }}</span>
						</div>
					</div>
				</div>
			</div>

			<!-- 空状态占位符 -->
			<div v-else class="no-data-container">
				<a-result status="404" title="暂无房源" sub-title="没有找到符合条件的房源，请尝试更改搜索或筛选条件"></a-result>
			</div>
		</a-spin>

		<!-- 分页组件 -->
		<a-flex justify="flex-end" class="pagination">
			<a-pagination
				size="small"
				@change="onPageChange"
				@showSizeChange="onPageSizeChange"
				show-size-changer
				:pageSizeOptions="['10', '20', '50', '100']"
				v-model:current="pageNo"
				v-model:page-size="pageSize"
				:total="totalCount"
				:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
				:locale="{ items_per_page: '条/页' }"
			/>
		</a-flex>
	</div>
</template>

<script>
	import userApi from '@/api/userApi';

	export default {
		name: 'HouseList',
		data() {
			return {
				searchQuery: '',
				selectedHouseType: '不限',
				selectedPriceRange: '不限',
				selectedAreaRange: '不限',
				selectedFloor: '不限',
				selectedDistrict: '不限',
				selectedStation: '不限',
				customPriceMin: null, // 自定义最小租金
				customPriceMax: null, // 自定义最大租金
				customAreaMin: null, // 自定义最小面积
				customAreaMax: null, // 自定义最大面积
				customFloorMin: null, // 自定义最小楼层
				customFloorMax: null, // 自定义最大楼层
				houseTypes: ['不限', '一房', '两房', '三房', '三房及以上'],
				priceRanges: ['不限', '500元以下', '800元以下', '1500元以下', '2000元以下'], // 租金选项
				areaRanges: ['不限', '30㎡以下', '30-50㎡', '50-70㎡', '70㎡及以上'], // 面积选项
				floors: ['不限', '一楼', '二楼', '三楼', '四楼', '五楼', '五楼及以上'], // 楼层选项
				businessArea: [
					'不限',
					'花都广场/区政府',
					'来又来/大润发',
					'白云国际机场',
					'新世纪广场',
					'花山',
					'狮岭',
					'雅瑶',
					'融创茂',
					'雅房乐锦城/保利花城',
					'骏壹万邦',
					'建设北路'
				],
				subwayStations: [
					'不限',
					'高增',
					'清塘',
					'清㘵',
					'莲塘',
					'马鞍山公园',
					'花都广场',
					'花果山公园',
					'花城路',
					'广州北站',
					'花都汽车城',
					'飞鹅岭'
				],
				pageNo: 1,
				pageSize: 10,
				totalCount: 0,
				houses: [], // 房源列表
				isSearchMode: false, // 标志是否为搜索模式
				originalHouses: [], // 用于保存搜索结果
				// 排序相关数据
				sortOptions: [
					{ label: '默认排序', value: null },
					{ label: '价格', value: 'price' },
					{ label: '面积', value: 'area' }
				],
				selectedSort: null, // 当前选中的排序字段
				sortOrder: 'asc', // 排序顺序，'asc' 升序，'desc' 降序
				isCustomFilter: false, // 用于标识是否使用自定义筛选
				loading: false
			};
		},
		methods: {
			search() {
				this.isSearchMode = true; // 标志当前为搜索模式
				this.pageNo = 1; // 重置分页
				this.searchHouses();
				this.$router.push({ path: '/house-list', query: { keyword: this.searchQuery } });
			},
			searchHouses() {
				this.loading = true;
				userApi
					.searchHouses(this.searchQuery, this.pageNo, this.pageSize)
					.then((res) => {
						this.houses = res.data.houses;
						this.originalHouses = res.data.houses; // 保存搜索结果用于后续筛选
						this.totalCount = res.data.total;
					})
					.catch((err) => {
						console.error('获取数据失败:', err);
					})
					.finally(() => {
						this.loading = false;
					});
			},

			// 筛选房源
			filterHouses() {
				this.loading = true;
				const filters = {};

				// 检查是否是自定义筛选
				const isCustomPrice = this.customPriceMin !== null || this.customPriceMax !== null;
				const isCustomArea = this.customAreaMin !== null || this.customAreaMax !== null;
				const isCustomFloor = this.customFloorMin !== null || this.customFloorMax !== null;

				// 如果是自定义筛选，清除所有的预设选中状态
				if (isCustomPrice) {
					this.selectedPriceRange = '不限'; // 清除租金预设选中状态
				}
				if (isCustomArea) {
					this.selectedAreaRange = '不限'; // 清除面积预设选中状态
				}
				if (isCustomFloor) {
					this.selectedFloor = '不限'; // 清除楼层预设选中状态
				}

				// 户型筛选逻辑
				if (this.selectedHouseType !== '不限') {
					const houseTypeMap = {
						一房: '1房',
						两房: '2房',
						三房: '3房',
						三房及以上: '3房及以上'
					};
					filters.houseType = houseTypeMap[this.selectedHouseType] || this.selectedHouseType;
				}

				// 租金筛选逻辑
				if (this.selectedPriceRange === '不限') {
					// 当自定义值均为空时重置为 null，否则使用自定义值
					if (this.customPriceMin === null && this.customPriceMax === null) {
						filters.priceMin = null;
						filters.priceMax = null;
					} else {
						filters.priceMin = this.customPriceMin || null;
						filters.priceMax = this.customPriceMax || null;
					}
				} else {
					// 使用预设选项
					const priceMap = {
						'500元以下': { priceMax: 500 },
						'800元以下': { priceMax: 800 },
						'1500元以下': { priceMax: 1500 },
						'2000元以下': { priceMax: 2000 }
					};
					filters.priceMax = priceMap[this.selectedPriceRange]?.priceMax || null;
				}

				// 面积筛选逻辑
				if (this.selectedAreaRange === '不限') {
					// 当自定义值均为空时重置为 null，否则使用自定义值
					if (this.customAreaMin === null && this.customAreaMax === null) {
						filters.areaMin = null;
						filters.areaMax = null;
					} else {
						filters.areaMin = this.customAreaMin || null;
						filters.areaMax = this.customAreaMax || null;
					}
				} else if (this.customAreaMin !== null || this.customAreaMax !== null) {
					// 自定义值优先
					filters.areaMin = this.customAreaMin || null;
					filters.areaMax = this.customAreaMax || null;
				} else {
					// 使用预设选项
					const areaMap = {
						'30㎡以下': { areaMax: 29 },
						'30-50㎡': { areaMin: 30, areaMax: 49 },
						'50-70㎡': { areaMin: 50, areaMax: 69 },
						'70㎡及以上': { areaMin: 70 }
					};
					filters.areaMin = areaMap[this.selectedAreaRange]?.areaMin || null;
					filters.areaMax = areaMap[this.selectedAreaRange]?.areaMax || null;
				}

				// 楼层筛选逻辑
				if (this.selectedFloor === '不限') {
					// 当自定义值均为空时重置为 null，否则使用自定义值
					if (this.customFloorMin === null && this.customFloorMax === null) {
						filters.floorMin = null;
						filters.floorMax = null;
					} else {
						filters.floorMin = this.customFloorMin || null;
						filters.floorMax = this.customFloorMax || null;
					}
				} else if (this.customFloorMin !== null || this.customFloorMax !== null) {
					// 自定义值优先
					filters.floorMin = this.customFloorMin || null;
					filters.floorMax = this.customFloorMax || null;
				} else {
					// 使用预设选项
					const floorMap = {
						一楼: { floorMin: 1, floorMax: 1 },
						二楼: { floorMin: 2, floorMax: 2 },
						三楼: { floorMin: 3, floorMax: 3 },
						四楼: { floorMin: 4, floorMax: 4 },
						五楼: { floorMin: 5, floorMax: 5 },
						五楼及以上: { floorMin: 5 }
					};
					filters.floorMin = floorMap[this.selectedFloor]?.floorMin || null;
					filters.floorMax = floorMap[this.selectedFloor]?.floorMax || null;
				}

				// 商圈筛选
				if (this.selectedDistrict === '不限') {
					filters.businessArea = null;
				} else {
					filters.businessArea = this.selectedDistrict;
				}

				// 地铁站筛选
				if (this.selectedStation === '不限') {
					filters.subwayStation = null;
				} else {
					filters.subwayStation = this.selectedStation;
				}
				//定义一个conditions，封装filters和keyword
				const conditions = {
					keyword: this.searchQuery || '',
					filters
				};

				//根据有无关键词来判断是直接筛选还是间接筛选
				if (this.searchQuery) {
					userApi
						.filterHousesByKey(conditions, this.pageNo, this.pageSize)
						.then((res) => {
							this.houses = res.data.houses;
							this.totalCount = res.data.total;
						})
						.catch((err) => {
							console.error('筛选失败:', err);
						})
						.finally(() => {
							this.loading = false;
						});
				} else {
					// 每次筛选都调用接口，获取新的数据
					userApi
						.filterHouses(filters, this.pageNo, this.pageSize)
						.then((res) => {
							this.houses = res.data.houses;
							this.totalCount = res.data.total;
						})
						.catch((err) => {
							console.error('筛选失败:', err);
						})
						.finally(() => {
							this.loading = false;
						});
				}
			},
			getAllHouses() {
				this.loading = true;
				userApi
					.getHouses(this.pageNo, this.pageSize) // 调用接口
					.then((res) => {
						this.houses = res.data.houses;
						this.totalCount = res.data.total; // 更新查询的总数
					})
					.catch((error) => {
						console.error('无法获取房源数据，请稍后再试:', error);
					})
					.finally(() => {
						this.loading = false;
					});
			},
			// 设置排序规则
			setSort(sortKey) {
				if (this.selectedSort === sortKey) {
					// 切换排序顺序
					this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				} else {
					// 更改排序规则，默认升序
					this.selectedSort = sortKey;
					this.sortOrder = 'asc';
				}
				this.sortHouses(); // 调用排序方法
			},
			// 排序房源
			sortHouses() {
				if (!this.selectedSort) return; // 默认排序，无需处理
				this.houses.sort((a, b) => {
					const valueA = a[this.selectedSort];
					const valueB = b[this.selectedSort];
					if (this.sortOrder === 'asc') {
						return valueA - valueB;
					} else {
						return valueB - valueA;
					}
				});
			},
			// 分页切换
			onPageChange(newPage) {
				this.pageNo = newPage;
				this.getAllHouses();
			},
			// 修改分页大小
			onPageSizeChange(current, size) {
				this.pageSize = size;
				this.pageNo = 1;
				this.getAllHouses();
			},
			goToDetails(houseId) {
				window.open(`/house-details/${houseId}`, '_blank');
			}
		},
		watch: {
			pageNo() {
				this.searchHouses();
			},
			'$route.query': {
				handler(newQuery) {
					if (newQuery.keyword) {
						this.searchQuery = newQuery.keyword;
						this.searchHouses(); // 根据新的关键字重新加载房源
					}
				},
				immediate: true // 在初始加载时立即触发
			}
		},
		created() {
			// 通过路由参数赋值
			if (this.$route.query.businessArea) {
				this.selectedDistrict = this.$route.query.businessArea;
			}
			if (this.$route.query.subwayStation) {
				this.selectedStation = this.$route.query.subwayStation;
			}
			if (this.$route.query.keyword) {
				this.searchQuery = this.$route.query.keyword; // 提取关键词到搜索框
			}
			// 通过商圈或地铁站名称筛选
			if (this.$route.query.businessArea || this.$route.query.subwayStation) {
				this.filterHouses();
			} else if (this.$route.query.keyword) {
				// 通过关键字搜索
				this.searchHouses();
			} else {
				//没有关键字也没有筛选条件，直接获取所有房源
				this.getAllHouses();
			}
		}
	};
</script>

<style scoped>
	.house-container {
		max-width: 1200px;
		margin: 0 auto;
		padding: 20px;
		background-color: #fff;
	}

	.search-bar {
		display: flex;
		margin-bottom: 20px;
		align-items: center;
	}

	.search-input-container {
		display: flex;
		align-items: center;
	}

	.search-input {
		width: 300px;
		margin-right: 10px;
	}

	.search-button {
		background-color: #e55a00;
		color: #fff;
	}

	.search-button:hover {
		color: #fff;
		background-color: #c14c00;
	}

	.filter-container {
		border: 1px solid #ddd;
		padding: 15px;
		margin-bottom: 2rem;
	}

	.filter-group {
		display: flex;
		align-items: center;
		margin-bottom: 1rem;
	}

	.filter-title {
		margin-right: 1rem;
		font-size: 14px;
		color: #555;
		font-weight: bold;
	}

	.filter-options {
		display: flex;
		flex-wrap: wrap;
		gap: 1rem;
		align-items: center;
	}

	.filter-option {
		font-size: 14px;
		color: #333; /* 默认文字颜色 */
		cursor: pointer;
		transition: color 0.3s;
	}

	.filter-option:hover {
		color: #e55a00;
		text-decoration: underline;
	}

	.filter-option.active {
		color: #e55a00; /* 选中时颜色变为橙色 */
	}

	.custom-range {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.custom-range input {
		width: 80px;
		padding: 5px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}

	.range-divider {
		color: #999;
		font-size: 14px;
	}

	.custom-range-button {
		background-color: #e55a00;
		color: #fff;
		border-color: #e55a00;
		font-size: 14px;
		padding: 4px 10px;
		height: auto;
		line-height: normal;
		border-radius: 4px;
	}

	.custom-range-button:hover {
		color: #fff;
		background-color: #c14c00;
	}

	.house-list {
		display: flex;
		flex-direction: column;
	}

	.house-item {
		display: flex;
		padding: 20px;
		border: none;
		border-top: 1px solid #ddd;
		cursor: pointer;
	}

	.house-item:hover {
		background: #f8f8f8;
	}

	.house-image {
		width: 200px;
		height: 150px;
		flex-shrink: 0;
		margin-right: 1.5rem;
	}

	.house-image img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.house-details {
		flex-grow: 1;
	}

	.house-title {
		font-size: 24px;
		font-weight: bold;
		color: #333;
		margin-bottom: 10px;
	}

	.house-item:hover .house-title {
		color: #e55a00;
		text-decoration: underline;
	}

	.house-info {
		display: flex;
		flex-direction: column; /* 让字段分行排列 */
		gap: 1rem; /* 行间距 */
		margin-top: 1rem;
	}

	.field-row {
		display: flex;
		gap: 1rem; /* 字段之间的间距 */
	}

	.field {
		padding: 5px 10px; /* 内间距 */
		background-color: RGB(243, 243, 251); /* 字段背景色 */
		border-radius: 4px; /* 圆角 */
		font-size: 13px;
		color: #515861;
		white-space: nowrap; /* 防止换行 */
	}

	.house-price {
		font-size: 22px;
		font-weight: bold;
		color: #e55a00;
		text-align: right;
	}

	.pagination {
		text-align: center;
		margin-top: 20px;
	}

	.sort-container {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 1rem 0;
	}

	.sort-options {
		display: flex;
		gap: 2rem;
	}

	.sort-option {
		font-size: 14px;
		color: #555;
		font-weight: bold;
		cursor: pointer;
	}

	.sort-option.active {
		color: #e55a00;
	}

	.sort-option:hover {
		text-decoration: underline;
		color: #e55a00;
	}

	.total-count {
		font-size: 14px;
		color: #333;
	}
</style>
